/*
		ServEngine framework library
		A library to fast develop JEE online applications
	
		Copyright 2008 José Ignacio de Córdoba Álvaro

		Licensed under the Apache License, Version 2.0 (the "License");
		you may not use this file except in compliance with the License.
		You may obtain a copy of the License at

				http://www.apache.org/licenses/LICENSE-2.0

		Unless required by applicable law or agreed to in writing, software
		distributed under the License is distributed on an "AS IS" BASIS,
		WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
		See the License for the specific language governing permissions and
		limitations under the License.
	
		Jose Ignacio de Cordoba Alvaro
		http://ignacio.decordoba.com
*/

package com.servengine.util;

import java.io.*;

public class AttachmentDataSource implements javax.activation.DataSource,java.io.Serializable
{
	String name,contenttype;
	private byte[] datos; // Con este escritor se mete la información en este DataSource
// Lo siguiente lo comento para que sea serializable.
//	private InputStream inputstream; // Para cuando se construye el objeto pasando directamente un InputStream (de la segunda forma)
/*	public AttachmentDataSource(String name)
	{	super();
		this.name=name;
		contenttype=(new MimetypesFileTypeMap()).getContentType(name);
	}
	public AttachmentDataSource(String name, String contenttype)
	{
		this.name=name;
		this.contenttype=contenttype;
	}*/
	public AttachmentDataSource(String name, String contenttype, InputStream inputstream) throws IOException
	{
		this.name=name;
		this.contenttype=contenttype;
		BufferedInputStream lector = new BufferedInputStream(inputstream,25000); // Suponemos que es más eficiente.
		ByteArrayOutputStream aux = new ByteArrayOutputStream();
		BufferedOutputStream escritor = new BufferedOutputStream(aux); // Suponemos que es más eficiente
		byte[]buffer = new byte[10000];
		int leidos=0;
		while ((leidos = inputstream.read(buffer,0,10000))>0)
			escritor.write(buffer,0,leidos);
		lector.close(); escritor.close();
		datos = aux.toByteArray();
	}
	public String getContentType()
	{
		return contenttype;
	}
	public String getName()
	{
		return name;
	}
	public OutputStream getOutputStream()
	{
		throw new IllegalStateException("Data cannot be written to this object using getOutputStream()");
	}
	public InputStream getInputStream()
	{
//		if (inputstream!=null && escritor==null)
//			return inputstream; // Por ejemplo, para cuando se construye con la clase de OReally, que devuelve el InputStream.
		return new ByteArrayInputStream(datos); // Para cuando se usa la mierda del uploadObject
	}
	public int size()
	{	return datos.length;
	}
}